import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MeetingRoom } from './entities/meeting-room.entity';
import { Repository } from 'typeorm';
import { PaginDto } from 'src/commen/dto';
import {
  CreateMeetingRommDto,
  UpdateMeetingRoom,
} from './dtos/meeting-room.dto';
import { omit } from 'lodash';

@Injectable()
export class MeetingRoomService {
  @InjectRepository(MeetingRoom)
  private repository: Repository<MeetingRoom>;

  initData() {
    const room1 = new MeetingRoom();
    room1.name = '木星';
    room1.capacity = 10;
    room1.equipment = '白板';
    room1.location = '一层西';

    const room2 = new MeetingRoom();
    room2.name = '金星';
    room2.capacity = 5;
    room2.equipment = '';
    room2.location = '二层东';

    const room3 = new MeetingRoom();
    room3.name = '天王星';
    room3.capacity = 30;
    room3.equipment = '白板，电视';
    room3.location = '三层东';

    this.repository.insert([room1, room2, room3]);
  }
  async list(params: PaginDto) {
    const { pageNo, pageSize } = params;
    const skipNumber = (pageNo - 1) * pageSize;
    const [meetings, totalCount] = await this.repository.findAndCount({
      skip: skipNumber,
      take: pageSize,
    });
    return {
      rows: meetings,
      totalCount,
    };
  }

  async store(createMeetingRoom: CreateMeetingRommDto) {
    const newMeeting = await this.repository.insert(createMeetingRoom);
    if (!newMeeting) {
      throw new BadRequestException('请求失败');
    }
    return '添加成功';
  }
  async updateMeetingRoom(data: UpdateMeetingRoom) {
    const meeting = await this.repository.findOneBy({
      id: data.id,
    });
    if (!meeting) {
      throw new BadRequestException('会议室不存在');
    }
    await this.repository.update({ id: data.id }, { ...omit(data, ['id']) });
    return '更新成功';
  }
  async findById(id: number) {
    return await this.repository.findOneBy({
      id,
    });
  }
  async delete(id: number) {
    await this.repository.delete(id);
    return '删除成功';
  }
}
